import React, { useEffect, useState } from 'react';
import { Modal, Descriptions, Tag, Spin, message, Typography } from 'antd';
import { CheckCircleOutlined, CloseCircleOutlined, SyncOutlined, MinusCircleOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import TaskRecordTable from '../TaskRecordTable';
import { fetchTaskRecords } from '../../../../../services/scanTask';
import type { ScanTaskInfo, TaskRecord } from '../../types';
import { STATUS_COLORS, TRIGGER_TYPE_LABELS } from '../../types';

const { Text } = Typography;

interface TaskDetailModalProps {
  visible: boolean;
  onCancel: () => void;
  scanTask: ScanTaskInfo | null;
}

const TaskDetailModal: React.FC<TaskDetailModalProps> = ({ 
  visible, 
  onCancel, 
  scanTask 
}) => {
  const [loading, setLoading] = useState(false);
  const [taskRecords, setTaskRecords] = useState<TaskRecord[]>([]);

  // 获取状态图标和颜色
  const getStatusConfig = (status: string) => {
    switch (status) {
      case 'SUCCESS':
        return { icon: <CheckCircleOutlined />, color: 'success', text: '成功' };
      case 'FAILED':
        return { icon: <CloseCircleOutlined />, color: 'error', text: '失败' };
      case 'RUNNING':
        return { icon: <SyncOutlined spin />, color: 'processing', text: '运行中' };
      case 'SKIPPED':
        return { icon: <MinusCircleOutlined />, color: 'default', text: '跳过' };
      default:
        return { icon: <MinusCircleOutlined />, color: 'default', text: status };
    }
  };

  // 计算总耗时
  const calculateTotalDuration = (startTime: string, endTime?: string) => {
    if (!endTime) return '-';
    
    const start = dayjs(startTime);
    const end = dayjs(endTime);
    const duration = end.diff(start, 'second');
    
    if (duration < 60) return `${duration}秒`;
    if (duration < 3600) return `${Math.floor(duration / 60)}分${duration % 60}秒`;
    
    const hours = Math.floor(duration / 3600);
    const minutes = Math.floor((duration % 3600) / 60);
    const seconds = duration % 60;
    return `${hours}时${minutes}分${seconds}秒`;
  };

  // 获取启用的任务类型
  const getEnabledTasks = (task: ScanTaskInfo) => {
    const tasks = [];
    if (task.saTask) tasks.push('SA分析');
    if (task.gitTask) tasks.push('Git分析');
    if (task.apmTask) tasks.push('APM分析');
    if (task.jarTask) tasks.push('JAR分析');
    if (task.statisticsTask) tasks.push('统计分析');
    return tasks;
  };

  // 加载任务记录
  const loadTaskRecords = async (unitScanTaskId: number) => {
    setLoading(true);
    try {
      const records = await fetchTaskRecords(unitScanTaskId);
      setTaskRecords(records);
    } catch (error) {
      console.error('加载任务记录失败:', error);
      message.error('加载任务记录失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (visible && scanTask) {
      loadTaskRecords(scanTask.unitTaskId);
    }
  }, [visible, scanTask]);

  if (!scanTask) return null;

  const statusConfig = getStatusConfig(scanTask.status);

  return (
    <Modal
      title={`扫描任务详情 #${scanTask.unitTaskId}`}
      open={visible}
      onCancel={onCancel}
      footer={null}
      width={1000}
      style={{ top: 20 }}
      bodyStyle={{ maxHeight: 'calc(100vh - 200px)', overflowY: 'auto' }}
    >
      <Spin spinning={loading}>
        <div style={{ marginBottom: 24 }}>
          {/* 基本信息 */}
          <Descriptions title="基本信息" column={2} size="small">
            <Descriptions.Item label="扫描任务ID">
              {scanTask.unitTaskId}
            </Descriptions.Item>
            <Descriptions.Item label="单元ID">
              {scanTask.unitId}
            </Descriptions.Item>
            <Descriptions.Item label="应用ID">
              {scanTask.appId}
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag icon={statusConfig.icon} color={statusConfig.color}>
                {statusConfig.text}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="触发方式">
              <Tag color="blue">
                {TRIGGER_TYPE_LABELS[scanTask.triggerType] || scanTask.triggerType}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="Git分支">
              {scanTask.gitBranch || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="开始时间">
              {dayjs(scanTask.startTime).format('YYYY-MM-DD HH:mm:ss')}
            </Descriptions.Item>
            <Descriptions.Item label="结束时间">
              {scanTask.endTime ? dayjs(scanTask.endTime).format('YYYY-MM-DD HH:mm:ss') : '-'}
            </Descriptions.Item>
            <Descriptions.Item label="总耗时">
              {calculateTotalDuration(scanTask.startTime, scanTask.endTime)}
            </Descriptions.Item>
            <Descriptions.Item label="Git CommitID">
              <Text code style={{ fontSize: '12px' }}>
                {scanTask.gitCommitId || '-'}
              </Text>
            </Descriptions.Item>
          </Descriptions>

          {/* 任务配置 */}
          <Descriptions title="任务配置" column={1} size="small" style={{ marginTop: 16 }}>
            <Descriptions.Item label="启用任务">
              <div>
                {getEnabledTasks(scanTask).map((task, index) => (
                  <Tag key={index} color="green" style={{ marginBottom: 4 }}>
                    {task}
                  </Tag>
                ))}
              </div>
            </Descriptions.Item>
            {scanTask.result && (
              <Descriptions.Item label="整体结果">
                <Text 
                  ellipsis={{ 
                    tooltip: scanTask.result
                  }}
                  style={{ 
                    display: '-webkit-box',
                    WebkitLineClamp: 3,
                    WebkitBoxOrient: 'vertical',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis'
                  }}
                >
                  {scanTask.result}
                </Text>
              </Descriptions.Item>
            )}
          </Descriptions>

          {/* 子任务记录 */}
          <div style={{ marginTop: 24 }}>
            <h4 style={{ marginBottom: 12, fontSize: '16px', fontWeight: 'bold' }}>
              子任务执行记录
            </h4>
            <TaskRecordTable data={taskRecords} loading={loading} />
          </div>
        </div>
      </Spin>
    </Modal>
  );
};

export default TaskDetailModal;